import APPUpdate, {
	getDownload
} from "./plugins/APPUpdate"
import successMp3 from '../../static/mp3/success.wav'
import warningMp3 from '../../static/mp3/warning.wav'
import errorMp3 from '../../static/mp3/error.wav'


export default {
	data() {
		return {
			token: null,
			needLogin: true,
			pageConfig: {
				pageIndex: 0,
				pageSize: 20,
				bottomEnd: false,
				bottomLoading: false
			},
			userInfo: {},
			interval: null,
		}
	},
	async onShow() {
		this.token = uni.getStorageSync("token") || null
		this.userInfo = uni.getStorageSync("userInfo") ? JSON.parse(uni.getStorageSync("userInfo")) : null
		if (this.needLogin && !this.token) {
			this.$onLoginError()
			return
		}
		await this.$onLaunched
		if (this.afterShow) this.afterShow()
	},
	async onLoad(e) {
		await this.$onLaunched
		if (this.afterLoad) this.afterLoad(e)
	},
	computed: {},
	methods: {

		/**
		 * APP启动
		 */
		appLaunch() {
			let self = this
			// #ifdef APP-PLUS
			// 版本校验
			APPUpdate()
			// 检查通知是否开启
			self.getNotificationAuthority()
			// #endif
			// 保持登录
			let local_token = uni.getStorageSync("localToken")
			if (local_token) {
				self.$api.loginPersistence({
					localToken: local_token
				}).then(res => {
					self.$isResolve()
					self.afterLogin(res)
				}).catch(e => {
					uni.removeStorageSync("token")
					uni.removeStorageSync("localToken")
					self.$onLoginError()
				})
			} else {
				self.$isResolve()
			}
		},
		/**
		 * 退出登录
		 */
		logout() {
			let self = this
			uni.showModal({
				title: '提示',
				content: "确定退出吗？",
				success: function(res) {
					if (res.confirm) {
						self.$api.logout().then(res => {
							self.removeUserStorage()
							self.$onLoginError()
						})
					}
				}
			})
		},

		/**
		 * 刷新用户信息
		 * @returns {Promise<unknown>}
		 */
		refreshUserInfo() {
			let self = this
			return new Promise((resolve, reject) => {
				self.$api.getUserInfo().then(res => {
					if (res.token) uni.setStorageSync('token', res.token);
					if (res.local_token) uni.setStorageSync('localToken', res.local_token);
					uni.setStorageSync('userInfo', JSON.stringify(res));
					self.userInfo = res
					resolve(res)
				})
			})
		},

		/**
		 * 登录后共通处理
		 * @param res
		 */
		afterLogin(res) {
			if (res.token) uni.setStorageSync('token', res.token);
			if (res.local_token) uni.setStorageSync('localToken', res.local_token);
			uni.setStorageSync('userInfo', JSON.stringify(res));
			this.userInfo = res
			if (res.token) {
				this.initUniPushLaunch()
			}
			this.$onLoginSuccess()
		},

		/**
		 * 清空缓存
		 */
		removeUserStorage() {
			uni.removeStorageSync("token")
			uni.removeStorageSync("userInfo")
			uni.removeStorageSync("localToken")
		},

		/** 判断权限 */
		judgeAuthority(role = []) {
			let authority = this.userInfo.characterKeyList ?? []
			// let authority = ['chejian', 'kg01']
			let isRole = false
			role.forEach(option => {
				if (isRole) return
				authority.forEach(item => {
					if (item === option) isRole = true
				})
			})
			return isRole
		},

		/**
		 * 手机震动或者播放声音
		 * @param {Object} type
		 */
		msgRemind(type) {
			if (type == 'vibrate') {
				//震动
				plus.device.vibrate(500);
			} else {
				//声音
				let main = plus.android.runtimeMainActivity();
				let RingtoneManager = plus.android.importClass("android.media.RingtoneManager");
				let uri = RingtoneManager.getActualDefaultRingtoneUri(main, RingtoneManager.TYPE_NOTIFICATION);
				let MediaPlayer = plus.android.importClass("android.media.MediaPlayer");
				let player = MediaPlayer.create(main, uri);
				player.setLooping(false);
				player.prepare();
				player.start();
			}
		},
		
		/**
		 * 手机震动
		 * @param {Number} times
		 * @param {Number} time
		 */
		handleVibrate(times = 1, time = 500) {
			let current = 1
			// #ifdef APP-PLUS
			this.interval = setInterval(() => {
				plus.device.vibrate(time);
				current++
				if (current >= times) {
					clearInterval(this.interval)
				}
			}, time + 500)
			// #endif
		},
	
		/**
		 * 播放音频
		 * @param {String} type
		 */	
		handleMediaPlayer(type = "") {
			// 默认使用手机系统提示音
			if (!type) {
				let main = plus.android.runtimeMainActivity();
				let RingtoneManager = plus.android.importClass("android.media.RingtoneManager");
				let uri = RingtoneManager.getActualDefaultRingtoneUri(main, RingtoneManager.TYPE_NOTIFICATION);
				let MediaPlayer = plus.android.importClass("android.media.MediaPlayer");
				let player = MediaPlayer.create(main, uri);
				player.setLooping(false);
				player.prepare();
				player.start();
			} else {
				let innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = type === 'success' ? successMp3 : (type === 'warning' ? warningMp3 : errorMp3);
				innerAudioContext.onPlay();
				// 播放结束 销毁当前实例
				// innerAudioContext.onEnded(function(){  
				// 	innerAudioContext.destroy();  
				// })
				setTimeout(() => {
					innerAudioContext.destroy()
				}, 2000)
				// 
				// 出错之后 销毁，重新创建实例
				innerAudioContext.onError((res) => {
					innerAudioContext.destroy();
					innerAudioContext = uni.createInnerAudioContext();
				});
			}
		}
	}
}
